<?php
session_start();
/*
 * Session variables:
 * $_SESSION['type'] [string] = user type of the logged in user
 * $_SESSION['authorised'] [boolean] = whether or not the current user is logged in
 * $_SESSION['view_building'] [serial] = id of the building to be viewed
 */
if(isset($_SESSION['authorised']) && $_SESSION['authorised'] == true)
{   
    if(isset($_SESSION['type']))
    {
        if($_SESSION['type'] == 'administrator')
        {
        	$building_id=$_SESSION['view_building'];
        	
        	$room_name=strtoupper(addslashes(pg_escape_string($_POST['room_name'])));
			$floor=addslashes(pg_escape_string($_POST['floor']));			
			$room_number=pg_escape_string($_POST['room_num']);
			$capacity=pg_escape_string($_POST['capacity']);
        	if($room_name==''||$room_number==''||$capacity==''||!is_numeric($capacity)||!is_numeric($room_number))
            {
            	$_SESSION['error']='Error in creating room. Put correct information in all fields.';
				header('Location:admin_alert.php');
                exit();
            }
			
			include('connection.inc');
            
            $sql = "SELECT * FROM rooms where room_number='$room_number' AND building_id='$building_id'";
            $result = pg_query($sql);
            
            $count = pg_num_rows($result);
            
            if($count >= 1)
            {
                $_SESSION['error']= 'Room already exists';
                 header('Location:admin_alert.php');
                exit();
            }
            else
            {
                $sql="INSERT INTO rooms (room_name, floor, room_number, capacity, building_id) VALUES ('$room_name', '$floor', '$room_number', '$capacity','$building_id')";
				$result=pg_query($sql);
				
				$sql = "SELECT * FROM rooms where room_name='$room_name' AND room_number=$room_number";
            	$result = pg_query($sql);
				$room_id = pg_fetch_result($result, 0, 'room_id');
				
				header('Location: admin_viewbuilding.php');
				exit();
				
            }
        }
        elseif($_SESSION['type'] == 'student')
        {
            header('Location: student_index.php');
            exit();
        }
        elseif($_SESSION['type'] == 'tutor')
        {
            header('Location: tutor_index.php');
            exit();
        }
        elseif($_SESSION['type'] == 'parent')
        {
            header('Location: parent_index.php');
            exit();
        }
    }
}
else
{
    header('Location: index.php');
}
?>
